package wt.hpad.model.holder;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.implments.SwipeItemMangerImpl;

import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import wt.hpad.R;
import wt.hpad.base.BaseHolder;
import wt.hpad.base.BaseRvSwAdapter;
import wt.hpad.dialog.SimpleDialog;
import wt.hpad.dialog.SimpleDialogHandler;
import wt.hpad.dialog.TimeLoadingDialog;
import wt.hpad.model.bean.DishDetail;
import wt.hpad.model.remote.HttpRequest;
import wt.hpad.utils.DialogUtil;

/**
 * Created by wt on 12.25.
 */

public class DishDetaiSwHolder extends BaseHolder<DishDetail> {
    private final Context mContext;
    private final BaseRvSwAdapter<DishDetail> mAdapter;
    private TextView tv_dishName_dd;
    private TextView tv_dishNum_dd;
    private TextView tv_tip_dd;
    private TextView tv_isCompleted_dd;
    private Button btn_retreate;
    private SwipeLayout swipe_dishdetail;
    private SwipeItemMangerImpl mItemManger;
    private Activity mActivity;
    private TimeLoadingDialog mLoadingDialog;
    private View line;

    public DishDetaiSwHolder(Context context, ViewGroup parent, BaseRvSwAdapter<DishDetail> adapter, int layoutID) {
        super(context, parent, adapter, layoutID);
        mContext = context;
        mAdapter = adapter;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    @Override
    public void setItemView(View itemView) {
        tv_dishName_dd = (TextView) itemView.findViewById(R.id.tv_dishName_dds);
        tv_dishNum_dd = (TextView) itemView.findViewById(R.id.tv_dishNum_dds);
        tv_isCompleted_dd = (TextView) itemView.findViewById(R.id.tv_isCompleted_dds);
        tv_tip_dd = (TextView) itemView.findViewById(R.id.tv_tip_dds);
        btn_retreate = (Button) itemView.findViewById(R.id.btn_retreat_dds);
        line = itemView.findViewById(R.id.lv);

        swipe_dishdetail = (SwipeLayout) itemView.findViewById(R.id.swipe_dishdetail);
        swipe_dishdetail.setShowMode(SwipeLayout.ShowMode.PullOut);
        swipe_dishdetail.setDragDistance(20);
        Map<SwipeLayout.DragEdge, View> dragEdgeMap =
                swipe_dishdetail.getDragEdgeMap();
        dragEdgeMap.clear();
        swipe_dishdetail.addDrag(SwipeLayout.DragEdge.Right, itemView.findViewById(R.id.bottom_wrapper));
        swipe_dishdetail.setOnDoubleClickListener(new SwipeLayout.DoubleClickListener() {
            @Override
            public void onDoubleClick(SwipeLayout layout, boolean surface) {
                mItemManger.closeAllItems();
            }
        });

    }

    @Override
    public void bindItemValue(final DishDetail bean) {
        final String dishName = bean.dishName;
        isHideSomeItem(bean);
        redAllTv();
        tv_isCompleted_dd.setText("(未上)");
        tv_dishName_dd.setText(bean.dishName);
        tv_tip_dd.setText(bean.tipOfCook);
        tv_dishNum_dd.setText(bean.dishNum + "");


        // "退菜"
        btn_retreate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mItemManger.removeShownLayouts(swipe_dishdetail);
                int pos = getLayoutPosition();
                // 退菜
                retreatDish(pos, bean);
                mItemManger.closeAllItems();
            }
        });
    }

    @Override
    public void bindSwItemValue(SwipeItemMangerImpl itemManger, DishDetail bean, int position) {
        mItemManger = itemManger;
        mItemManger.bindView(this.itemView, position);
        bindItemValue(bean);
    }

    // item涂红
    private void redAllTv() {
        tv_dishName_dd.setTextColor(Color.rgb(255, 0, 0));
        tv_dishNum_dd.setTextColor(Color.rgb(255, 0, 0));
        tv_isCompleted_dd.setTextColor(Color.rgb(255, 0, 0));
        tv_tip_dd.setTextColor(Color.rgb(255, 0, 0));
    }

    /**
     * 退菜
     * 1.输入退菜数量
     */
    private void retreatDish(final int pos, final DishDetail dish) {
        final SimpleDialog inputRtNum = new SimpleDialog(mContext, mActivity,
                R.layout.dialog_edittext,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        View rootView = inputRtNum.getRootView();
        inputRtNum.setTitle("退菜数量");
        // 把dish num 显示出来
        final EditText edt_rt_num = (EditText) rootView.findViewById(R.id.edt_content);
        edt_rt_num.setText(String.valueOf(dish.dishNum));
        edt_rt_num.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        edt_rt_num.selectAll();
        inputRtNum.setHandler(new SimpleDialogHandler() {
            @Override
            public void onConfirm() {
                String inputNum = edt_rt_num.getText().toString();
                if (TextUtils.isEmpty(inputNum)) {
                    return;
                } else {
                    Integer result = Integer.parseInt(inputNum);
                    int rtNum = result.intValue();
                    if (rtNum > dish.dishNum || rtNum <= 0) {
                        DialogUtil.showToastOnUI("输入数量超出范围");
                    } else {
                        inputRtNum.endDialog();
                        handleRetreat(pos, rtNum);
                    }
                }
            }

            @Override
            public void onCancel() {
            }
        });
        inputRtNum.show();

    }


    /**
     * 退菜
     * 2.给定退菜理由,分为:选择已有 和 输入,2种
     */
    private void handleRetreat(final int pos, final int rtNum) {
        // 2.选择退菜理由
        final SimpleDialog excepDialog = new SimpleDialog(mContext, mActivity,
                R.layout.dialog_retreat_exception,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        final View rootView = excepDialog.getRootView();
        final RadioGroup radioGroup = (RadioGroup) rootView.findViewById(R.id.rg_exc);
        final RadioButton rbt_exc_other = (RadioButton) rootView.findViewById(R.id.rbt_exc_other);

        // 理由为"其他"
        rbt_exc_other.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 输入自定义的退菜理由
                handleInputException(pos, rtNum);
                excepDialog.endDialog();
            }
        });

        // 理由为已给出的
        excepDialog.setHandler(new SimpleDialogHandler() {
            @Override
            public void onConfirm() {
                int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
                if (checkedRadioButtonId == -1) {
                    return;
                } else {
                    final RadioButton checkedRbt = (RadioButton) rootView.findViewById(checkedRadioButtonId);

                    handleEndRetreat(pos, rtNum, checkedRbt.getText().toString());
                    excepDialog.endDialog();
                }
            }

            @Override
            public void onCancel() {
            }
        });

        excepDialog.show();
    }

    /**
     * 退菜
     * 3.输入的退菜理由
     */
    private void handleInputException(final int pos, final int rtNum) {
        final SimpleDialog inputException = new SimpleDialog(mContext, mActivity,
                R.layout.dialog_edittext,
                R.id.btn_dialog_confirm,
                R.id.btn_dialog_cancel);
        final View rootView = inputException.getRootView();
        inputException.setHandler(new SimpleDialogHandler() {
            @Override
            public void onConfirm() {
                EditText edt_content = (EditText) rootView.findViewById(R.id.edt_content);
                String content = edt_content.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return;
                } else {
                    handleEndRetreat(pos, rtNum, content);
                    inputException.endDialog();
                }
            }

            @Override
            public void onCancel() {
            }
        });
        inputException.show();
    }

    /**
     * 退菜
     * 4.完成退菜: 发送退菜到服务器
     */
    private void handleEndRetreat(int pos, int rtNum, String tipOfException) {
        // 界面处理
        DishDetail dishDetail = mAdapter.getDatas().get(pos);
        int result = dishDetail.dishNum - rtNum;
        if (result == 0) { // 全退完则删除该记录
            mAdapter.getDatas().remove(pos);
            mAdapter.removeItem(pos);
        } else {    // 否则,更改未上菜的数量
            dishDetail.dishNum = result;
            mAdapter.notifyItemChanged(pos);
        }
        // msg to server 退菜

        final HttpRequest httpRequest = new HttpRequest();
        // 从服务器获取新数据,并更新数据库
        final Observer<Integer> rtObsr = getRtObsr();
        httpRequest.handleRetreatDish(rtObsr, dishDetail.sid, rtNum, tipOfException);
        mLoadingDialog = new TimeLoadingDialog.Builder()
                .setActivity(mActivity)
                .setStartContent("操作中...")
                .setEndContent("退菜完成")
                .setfailContent("退菜失败")
                .setHandler(new SimpleDialogHandler() {
                    @Override
                    public void onConfirm() {
                    }

                    @Override
                    public void onCancel() {
                        httpRequest.stopHandlerAction();
                        rtObsr.onError(new Throwable());
                    }
                }).build();
        mLoadingDialog.start();
    }

    private Observer<Integer> getRtObsr() {
        return new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Integer value) {
                mLoadingDialog.end();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        };
    }

    /**
     * 如果没有"口味"则隐藏之
     */
    private void isHideSomeItem(DishDetail bean) {
        if (TextUtils.isEmpty(bean.tipOfCook)) {
            tv_tip_dd.setVisibility(View.GONE);
            line.setVisibility(View.GONE);
        } else {
            tv_tip_dd.setVisibility(View.VISIBLE);
            line.setVisibility(View.VISIBLE);
            tv_tip_dd.setText(bean.tipOfCook);
        }
    }
}
